<!-- 开始节点的属性表单 -->
<template>
    <div class="collapse-content-box">
        <div class="option">
            <span class="title item-required"> {{ t('attributeFrom.nodeName') }} </span>
            <div class="form-item">
                <a-input v-model:value="form.processNodeName" @change="handleFormChange" />
            </div>
        </div>
        <!-- 开始 -->
        <div class="start-element-wrapper">
            <!-- 关联数据源 -->
            <div class="option">
                <span class="title item-required">
                    {{ t('attributeFrom.datasource') }}
                </span>
                <div class="form-item">
                    <a-select v-model:value="form.associatedDataSource" @change="handleChangeDataSource">
                        <a-select-option v-for="approve in dataSource" :key="approve.id" :value="approve.id">
                            {{ approve.name }}
                        </a-select-option>
                    </a-select>
                </div>
            </div>
            <!-- 触发类型 -->
            <div class="option">
                <span class="title">
                    {{ t('attributeFrom.triggerType') }}
                </span>
                <div class="form-item">
                    <a-radio-group v-model:value="form.triggerConfiguration.triggerType" @change="handleFormChange">
                        <a-radio v-for="type in triggerTypeOptions" :key="type.key" :value="type.key">
                            {{ type.title }}
                        </a-radio>
                    </a-radio-group>
                </div>
            </div>
            <!-- 定时触发 -->
            <template v-if="form.triggerConfiguration.triggerType === 'TIMING_TRIGGER'">
                <!-- 触发频率 -->
                <div class="option">
                    <span class="title">
                        {{ t('attributeFrom.triggerFrequency') }}
                    </span>
                    <div class="form-item">
                        <a-radio-group
                            v-model:value="form.triggerConfiguration.timingTriggerConfiguration.triggerFrequency"
                            @change="handleFormChange"
                        >
                            <a-radio v-for="type in triggerFrequencyOptions" :key="type.key" :value="type.key">
                                {{ type.title }}
                            </a-radio>
                        </a-radio-group>
                    </div>
                </div>
                <!-- 仅一次触发时机 -->
                <div
                    v-show="form.triggerConfiguration.timingTriggerConfiguration.triggerFrequency === 'ONLY_ONCE'"
                    class="option"
                >
                    <span class="title">
                        {{ t('attributeFrom.triggerTiming') }}
                    </span>
                    <div class="form-item">
                        <a-date-picker
                            v-model:value="
                                form.triggerConfiguration.timingTriggerConfiguration.onlyOnceTriggerConfiguration
                                    .triggerTiming
                            "
                            show-time
                            format="YYYY-MM-DD HH:mm:ss"
                            valueFormat="YYYY-MM-DD HH:mm:ss"
                            @change="handleFormChange"
                        />
                    </div>
                </div>
                <!-- 周期触发时机 -->
                <div
                    v-show="form.triggerConfiguration.timingTriggerConfiguration.triggerFrequency === 'PERIOD_TRIGGER'"
                    class="option"
                >
                    <span class="title">
                        {{ t('attributeFrom.triggerTiming') }}
                    </span>
                    <div class="form-item">
                        <a-range-picker
                            v-model:value="form.periodTriggerTiming"
                            format="YYYY-MM-DD"
                            valueFormat="YYYY-MM-DD"
                            @change="handlePeriodTriggerTiming"
                        />
                    </div>
                </div>
                <div
                    v-show="form.triggerConfiguration.timingTriggerConfiguration.triggerFrequency === 'PERIOD_TRIGGER'"
                    class="option cron-frame"
                >
                    <span class="title">
                        {{ t('attributeFrom.triggerWeek') }}
                    </span>
                    <div class="form-item">
                        <!-- cron-tab 组件 -->
                        <a-button @click="showCronSetting">设置触发周期</a-button>
                        <ul>
                            <li v-for="item in predictedList" :key="item">{{ item }}</li>
                        </ul>
                    </div>
                </div>
                <!-- 待办有效期 -->
                <div class="option">
                    <span class="title">
                        {{ t('attributeFrom.toDoValidity') }}
                    </span>
                    <div class="form-item">
                        <a-select
                            v-model:value="form.triggerConfiguration.toDoValidityPeriodConfiguration.type"
                            @change="handleFormChange"
                        >
                            <a-select-option v-for="todo in toDoValidityOptions" :key="todo.key" :value="todo.key">
                                {{ todo.title }}
                            </a-select-option>
                        </a-select>
                    </div>
                </div>
                <!-- 自定义待办有效期 -->
                <div
                    v-if="form.triggerConfiguration.toDoValidityPeriodConfiguration.type === 'CUSTOMIZE'"
                    class="option"
                >
                    <span class="title"></span>
                    <div class="form-item custom-validity">
                        <a-input-number
                            v-model:value="form.triggerConfiguration.toDoValidityPeriodConfiguration.length"
                            @change="handleFormChange"
                        />
                        <a-select
                            v-model:value="form.triggerConfiguration.toDoValidityPeriodConfiguration.timeUnit"
                            @change="handleFormChange"
                        >
                            <a-select-option v-for="todo in dateType" :key="todo.key" :value="todo.key">
                                {{ todo.title }}
                            </a-select-option>
                        </a-select>
                    </div>
                </div>
            </template>
            <!-- 即时触发 -->
            <template v-else>
                <!-- 触发时机 -->
                <div class="option">
                    <span class="title">
                        {{ t('attributeFrom.triggerTiming') }}
                    </span>
                    <div class="form-item">
                        <a-checkbox-group
                            v-model:value="form.triggerConfiguration.instantTriggerConfiguration.triggerTimingList"
                            @change="handleFormChange"
                        >
                            <a-checkbox v-for="time in timingList" :key="time.key" :value="time.key">
                                {{ time.title }}
                            </a-checkbox>
                        </a-checkbox-group>
                    </div>
                </div>
                <!-- 触发条件 -->
<!--                <div class="trigger-condition">-->
<!--                    <a-button-->
<!--                        v-if="-->
<!--                            form.triggerConfiguration.triggeringConditions &&-->
<!--                            !isEmpty(form.triggerConfiguration.triggeringConditions)-->
<!--                        "-->
<!--                        type="primary"-->
<!--                        @click="triggerModalVisible = true"-->
<!--                    >-->
<!--                        {{ t('attributeFrom.triggeringConditioned') }}-->
<!--                    </a-button>-->
<!--                    <a-button v-else :disabled="!Boolean([].length)" @click="triggerModalVisible = true">-->
<!--                        {{ t('attributeFrom.addTriggeringConditioned') }}-->
<!--                    </a-button>-->
<!--                </div>-->
            </template>
            <!-- 添加触发条件弹框 -->
            <triggerModal ref="triggerModal" />
        </div>
        <a-modal
            v-model:visible="cronSettingVisible"
            :title="t('attributeFrom.setTriggerCycle')"
            @ok="confirmCronSetting"
            @cancel="cancelCronSetting"
        >
            <Cron v-model:value="tempCron" :startTime="form.periodTriggerTiming[0]" :showExpression="false" />
        </a-modal>
        <!-- 结束 -->
    </div>
</template>

<script lang="ts">
    import { defineComponent, ref, watch, onMounted, computed } from 'vue'
    import { cloneDeep } from 'lodash-es'
    import { useI18n } from 'vue-i18n'
    import triggerModal from './triggerModal.vue'
    import { isEmpty } from '@/utils/is'
    import { message } from 'ant-design-vue'
    import {
        triggerTypeOptions,
        triggerFrequencyOptions,
        toDoValidityOptions,
        dateType,
        timingList
    } from './constantTable'
    // api
    import { getWorkFlowDataSource } from '@/apis/sys/workFlow'
    import { Cron, Predicted } from 'allin-taishan-component'
    const DEFAULT_CRON = '0 0 * * * ? *'

    interface startNodeAttributeForm {
        // TODO 开始节点属性表单的接口，开发该组件时定义
        [key: string]: any
    }
    export default defineComponent({
        components: {
            triggerModal,
            Cron
        },
        props: {
            processType: {
                type: String,
                default: ''
            },
            applicationId: {
                type: Number
            },
            processNodeForm: {
                type: Object,
                default: () => ({})
            }
        },
        emits: ['change', 'selectDataSource'],
        setup(props, { emit }) {
            // 国际化
            const { t } = useI18n()

            const form = ref<startNodeAttributeForm>({})

            // 数据源
            const dataSource = ref([])
            // 临时Cron表达式
            const tempCron = ref<string>('')

            // 条件列表弹窗
            const triggerModalVisible = ref<boolean>(false)

            // 条件列表弹窗-DOM元素
            const triggerModal = ref()
            // 从processNodeForm属性中，获取当前组件需要的表单数据，构造一个新的表单
            function initForm() {
                // 构造开始节点属性表单的逻辑
                const { associatedDataSource, triggerConfiguration, processNodeName } = cloneDeep(
                    props.processNodeForm || {}
                )
                const { timingTriggerConfiguration } = triggerConfiguration
                const { periodTriggerConfiguration } = timingTriggerConfiguration
                let triggerTimingArr: Array<string> = []
                if (periodTriggerConfiguration?.triggerStartTime && periodTriggerConfiguration?.triggerEndTime) {
                    triggerTimingArr = [
                        periodTriggerConfiguration?.triggerStartTime,
                        periodTriggerConfiguration?.triggerEndTime
                    ]
                }
                if (!periodTriggerConfiguration) {
                    timingTriggerConfiguration.periodTriggerConfiguration = {
                        triggerPeriod: DEFAULT_CRON
                    }
                    tempCron.value = DEFAULT_CRON
                } else {
                    tempCron.value = periodTriggerConfiguration.triggerPeriod
                }
                form.value = {
                    associatedDataSource,
                    triggerConfiguration,
                    processNodeName,
                    periodTriggerTiming: triggerTimingArr.length ? triggerTimingArr : []
                }
            }

            watch(
                () => props.processNodeForm,
                () => {
                    // processNodeForm发生变化时，重新初始化一下开始节点属性表单
                    initForm()
                },
                {
                    deep: true,
                    immediate: true
                }
            )

            // 表单数据发生变化，向组件外抛出change事件
            function handleFormChange() {
                emit('change', cloneDeep(form.value))
            }

            const handlePeriodTriggerTiming = () => {
                const {
                    periodTriggerTiming,
                    triggerConfiguration: {
                        timingTriggerConfiguration: { periodTriggerConfiguration }
                    }
                } = form.value
                form.value.triggerConfiguration.timingTriggerConfiguration.periodTriggerConfiguration = {
                    triggerStartTime: periodTriggerTiming.length && periodTriggerTiming[0],
                    triggerEndTime: periodTriggerTiming.length && periodTriggerTiming[1],
                    triggerPeriod: periodTriggerConfiguration?.triggerPeriod
                }
                handleFormChange()
            }

            // 设置触发条件
            const handleSetTriggering = () => {
                triggerModal.value &&
                    triggerModal.value.handleSaveData().then(data => {
                        if (data) {
                            // 如果添加了条件，就必须要选择一个规则
                            for (let i = 0, len = data.length; i < len; i++) {
                                if (data[i].rule && isEmpty(data[i].rule)) {
                                    return message.warning(t('attributeFrom.error'))
                                }
                            }
                            triggerModalVisible.value = false
                            form.value.triggerConfiguration.triggeringConditions = data
                        }
                    })
            }

            // 切换数据源
            const handleChangeDataSource = () => {
                form.value.triggerConfiguration.triggeringConditions.componentHideRule.rules = []
                emit('selectDataSource', form.value.associatedDataSource)
                handleFormChange()
            }

            const getDataSource = associatedDataSource => {
                return new Promise(resolve => {
                    const data = {
                        pageNo: 1,
                        pageSize: 100,
                        filter: {} as { createType?: string; applicationId?: string | number }
                    }

                    /**
                     * 表单的就正常，filter里放applicationId
                     * 系统的filter里只传 "createType" : "SYSTEM_MANAGEMENT"
                     */
                    if (props.processType === 'SYSTEM_MANAGEMENT') {
                        data.filter.createType = props.processType
                    } else {
                        data.filter.applicationId = props.applicationId
                    }

                    // 获取数据源
                    getWorkFlowDataSource(data).then(res => {
                        dataSource.value = res
                        resolve(associatedDataSource)
                    })
                })
            }

            const cronSettingVisible = ref<boolean>(false)
            const showCronSetting = () => {
                cronSettingVisible.value = true
            }
            const confirmCronSetting = () => {
                form.value.triggerConfiguration.timingTriggerConfiguration.periodTriggerConfiguration.triggerPeriod =
                    tempCron.value
                cronSettingVisible.value = false
                handleFormChange()
            }
            const cancelCronSetting = () => {
                tempCron.value =
                    form.value.triggerConfiguration.timingTriggerConfiguration.periodTriggerConfiguration.triggerPeriod
                cronSettingVisible.value = false
            }
            const predictedList = computed(() => {
                const {
                    triggerConfiguration: {
                        timingTriggerConfiguration: { periodTriggerConfiguration, triggerFrequency }
                    },
                    periodTriggerTiming
                } = form.value
                if (triggerFrequency === 'PERIOD_TRIGGER' && periodTriggerConfiguration?.triggerPeriod) {
                    const predicted = new Predicted(periodTriggerConfiguration.triggerPeriod, periodTriggerTiming?.[0])
                    return predicted.resultList
                } else {
                    return []
                }
            })

            // 生命周期
            onMounted(() => {
                const { associatedDataSource } = cloneDeep(props.processNodeForm)
                // 获取数据源
                getDataSource(associatedDataSource)
            })

            return {
                // 组件属性
                form,
                // 数据源
                dataSource,
                // 条件列表弹窗
                triggerModalVisible,
                t,
                // 组件方法
                handleFormChange,
                handleChangeDataSource,
                isEmpty: isEmpty,
                /**
                 * 循环的数组常量
                 * triggerTypeOptions,triggerFrequencyOptions,toDoValidityOptions,dateType,timingList,
                 */
                triggerTypeOptions,
                triggerFrequencyOptions,
                toDoValidityOptions,
                dateType,
                timingList,
                // 条件列表弹窗-DOM元素
                triggerModal,
                // 设置触发条件
                handleSetTriggering,
                cronSettingVisible,
                tempCron,
                showCronSetting,
                confirmCronSetting,
                cancelCronSetting,
                predictedList,
                handlePeriodTriggerTiming
            }
        }
    })
</script>

<style lang="less" scoped>
    .start-element-wrapper {
        &.item-required {
            &:before {
                display: inline-block;
                margin-right: 4px;
                color: #f5222d;
                font-size: 14px;
                font-family: SimSun, sans-serif;
                line-height: 1;
                content: '*';
            }
        }

        .custom-validity {
            display: flex;

            :deep(.@{ant-prefix}-input) {
                flex: 1;
            }

            :deep(.@{ant-prefix}-select) {
                width: 70px;
                margin-left: 15px;
            }
        }

        :deep(.el-row) {
            flex: 1;
            flex-direction: column;
        }

        :deep(.el-col-16),
        :deep(.el-col-8) {
            width: 100%;
        }

        :deep(.el-tabs__content) {
            overflow: auto;
        }

        :deep(.@{ant-prefix}-checkbox-wrapper) {
            width: 100%;
        }

        :deep(.@{ant-prefix}-checkbox-wrapper + .@{ant-prefix}-checkbox-wrapper) {
            margin-left: 0;
            margin-top: 5px;
        }

        .trigger-condition {
            :deep(.@{ant-prefix}-btn) {
                width: 100%;
                margin-top: 15px;
            }
        }
    }
</style>

<i18n>
zh-CN:
  attributeFrom:
    datasource: '关联数据源'
    triggerType: '触发类型'
    triggerFrequency: '触发频率'
    triggerTiming: '触发时机'
    triggerWeek: '触发周期'
    setTriggerCycle: '设置触发周期'
    toDoValidity: '待办有效期'
    triggeringConditioned: '已设置触发条件'
    addTriggeringConditioned: '添加触发条件'
    nodeName: '节点名称'
en-US:
  attributeFrom:
    datasource: 'Associated data source'
    triggerType: 'Trigger type'
    triggerFrequency: 'Trigger Frequency'
    triggerTiming: 'Trigger Timing'
    triggerWeek: 'Trigger cycle'
    setTriggerCycle: 'Set Trigger Cycle'
    toDoValidity: 'ToDo Validity'
    triggeringConditioned: 'Trigger condition set'
    addTriggeringConditioned: 'Add trigger condition'
    nodeName: 'Node name'
</i18n>
